﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using KC.Framework.Tenant;
using KC.Service.Storage;
using KC.Model.Storage.Table;
using Microsoft.AspNetCore.Mvc.Rendering;
using KC.Framework.Extension;
using KC.Framework.Base;

namespace KC.Web.Admin.Controllers
{
    [MVC.Core.Extension.MenuFilter("日志管理", "系统日志管理", "/NLog/Index",
        Version = TenantConstant.DefaultVersion, TenantType = TenantConstant.DefaultTenantType, SmallIcon = "fa fa-file", AuthorityId = "A13E86D8-47B9-4A46-9B83-7D9EBA9D3026",
        DefaultRoleId = RoleConstants.AdminRoleId, Order = 2, IsExtPage = false, Level = 3)]
    public class NLogController : AdminBaseController
    {
        protected INoSqlService _tableService => ServiceProvider.GetService<INoSqlService>();
        public NLogController(
            IServiceProvider serviceProvider,
            ILogger<NLogController> logger)
            : base(serviceProvider, logger)
        {
        }

        [MVC.Core.Extension.PermissionFilter("系统日志管理", "系统日志管理", "/NLog/Index", "A13E86D8-47B9-4A46-9B83-7D9EBA9D3026",
            DefaultRoleId = RoleConstants.AdminRoleId, Order = 1, IsPage = true, ResultType = ResultType.ActionResult, AuthorityId = "A13E86D8-47B9-4A46-9B83-7D9EBA9D3026")]
        public ActionResult Index()
        {
            var tableType = EnumExtensions.GetEnumDictionary<NLogTableType>();
            ViewBag.tableType =
                tableType.Select(item => new SelectListItem { Text = item.Value, Value = item.Key.ToString() }).ToList();

            return View();
        }

        //根据条件获取相应的Json日志数据
        //[MVC.Core.Extension.PermissionFilter("系统日志管理", "加载系统日志列表数据", "/NLog/GetNLogJson",
        //    DefaultRoleId = RoleConstants.AdminRoleId, Order = 1, IsPage = false, ResultType = ResultType.JsonResult, AuthorityId = "B295D04C-7908-4CF3-8F6C-381488EA46D0")]
        public JsonResult GetNLogJson(int page = 1, int rows = 10, string logLevel = "", int tableType = 0)
        {
            var tableName = (NLogTableType)tableType;
            var result = _tableService.GetNLogInfosByTableNameAndPage(tableName, page, rows, logLevel);
            return Json(result);
        }

        //根据条件删除单条日志或清空日志
        [MVC.Core.Extension.PermissionFilter("系统日志管理", "删除系统日志", "/NLog/DeleteNLog", "1BF23319-EBEF-4E31-845E-8F1A1EC87529",
            DefaultRoleId = RoleConstants.AdminRoleId, Order = 2, IsPage = false, ResultType = ResultType.JsonResult, AuthorityId = "1BF23319-EBEF-4E31-845E-8F1A1EC87529")]
        public JsonResult DeleteNLog(string rowKey = "", int tableType = 0)
        {
            return GetServiceJsonResult(() =>
            {
                var tableName = (NLogTableType)tableType;
                return _tableService.DeleteNLog(tableName, rowKey);
            });
        }
    }
}